"""
样式引擎
负责解析、应用和管理组件样式，支持Element UI风格的样式系统
"""

import re
from typing import Dict, Any, Optional, Union, List
from .theme_manager import theme_manager
from .themes import Theme


class StyleProperties:
    """样式属性映射类"""
    
    # CSS到QML属性映射表
    CSS_TO_QML_MAPPING = {
        # 颜色相关
        'color': 'color',
        'background-color': 'color',
        'border-color': 'border.color',
        
        # 尺寸相关
        'width': 'width',
        'height': 'height',
        'min-width': 'minimumWidth', 
        'min-height': 'minimumHeight',
        'max-width': 'maximumWidth',
        'max-height': 'maximumHeight',
        
        # 边框相关
        'border-width': 'border.width',
        'border-style': 'border.style',
        'border-radius': 'radius',
        
        # 间距相关
        'margin': 'anchors.margins',
        'margin-top': 'anchors.topMargin',
        'margin-right': 'anchors.rightMargin', 
        'margin-bottom': 'anchors.bottomMargin',
        'margin-left': 'anchors.leftMargin',
        'padding': 'padding',
        
        # 字体相关
        'font-size': 'font.pixelSize',
        'font-family': 'font.family',
        'font-weight': 'font.weight',
        'line-height': 'lineHeight',
        
        # 布局相关
        'display': 'visible',
        'opacity': 'opacity',
        'z-index': 'z',
        
        # 定位相关
        'position': 'anchors',
        'top': 'anchors.top',
        'right': 'anchors.right',
        'bottom': 'anchors.bottom', 
        'left': 'anchors.left',
    }


class StyleResolver:
    """样式解析器"""
    
    def __init__(self):
        self.theme_manager = theme_manager
    
    def resolve_style_value(self, value: str) -> str:
        """
        解析样式值，支持主题变量引用
        
        例如：
        - "var(--primary-color)" -> "#409EFF"
        - "var(--font-size-base)" -> "14px"  
        - "20px" -> "20px"
        """
        if not isinstance(value, str):
            return str(value)
        
        # 解析CSS变量引用: var(--variable-name)
        var_pattern = r'var\(--([^)]+)\)'
        matches = re.finditer(var_pattern, value)
        
        result = value
        for match in matches:
            var_name = match.group(1)
            var_value = self.theme_manager.get_variable(var_name)
            
            if var_value is not None:
                result = result.replace(match.group(0), str(var_value))
        
        return result
    
    def resolve_color_value(self, color_name: str) -> str:
        """解析颜色值"""
        # 如果是十六进制颜色值，直接返回
        if color_name.startswith('#'):
            return color_name
        
        # 如果是RGB或RGBA值，直接返回
        if color_name.startswith(('rgb', 'rgba')):
            return color_name
        
        # 否则作为主题颜色名称查找
        return self.theme_manager.get_color(color_name, color_name)
    
    def resolve_size_value(self, size_value: str) -> str:
        """解析尺寸值"""
        # 如果包含单位，直接返回
        if any(unit in size_value for unit in ['px', 'em', 'rem', '%', 'pt']):
            return size_value
        
        # 否则作为主题尺寸名称查找
        return self.theme_manager.get_size(size_value, size_value)


class StyleEngine:
    """
    样式引擎 - Element UI风格样式系统的核心
    
    功能：
    - 解析CSS样式到QML属性
    - 应用主题变量
    - 管理组件样式状态  
    - 响应主题变更
    """
    
    def __init__(self):
        self.resolver = StyleResolver()
        self.component_styles = {}  # 组件样式缓存
        self._style_cache = {}      # 解析结果缓存
    
    def parse_css_style(self, css_style: Union[str, dict]) -> Dict[str, Any]:
        """
        解析CSS样式为QML属性字典
        
        Args:
            css_style: CSS样式字符串或字典
            
        Returns:
            dict: QML属性字典
        """
        if isinstance(css_style, str):
            css_style = self._parse_css_string(css_style)
        
        if not isinstance(css_style, dict):
            return {}
        
        # 检查缓存
        cache_key = str(sorted(css_style.items()))
        if cache_key in self._style_cache:
            return self._style_cache[cache_key]
        
        qml_properties = {}
        
        for css_prop, css_value in css_style.items():
            # 解析样式值（包含主题变量）
            resolved_value = self.resolver.resolve_style_value(str(css_value))
            
            # 映射CSS属性到QML属性
            qml_prop = StyleProperties.CSS_TO_QML_MAPPING.get(css_prop)
            
            if qml_prop:
                # 处理嵌套属性（如 border.color）
                if '.' in qml_prop:
                    self._set_nested_property(qml_properties, qml_prop, resolved_value)
                else:
                    qml_properties[qml_prop] = resolved_value
            else:
                # 如果没有映射，保持原属性名
                qml_properties[css_prop] = resolved_value
        
        # 缓存结果
        self._style_cache[cache_key] = qml_properties
        
        return qml_properties
    
    def _parse_css_string(self, css_string: str) -> Dict[str, str]:
        """解析CSS字符串为属性字典"""
        properties = {}
        
        # 移除注释
        css_string = re.sub(r'/\*.*?\*/', '', css_string, flags=re.DOTALL)
        
        # 分割CSS声明
        declarations = [decl.strip() for decl in css_string.split(';') if decl.strip()]
        
        for declaration in declarations:
            if ':' in declaration:
                prop, value = declaration.split(':', 1)
                properties[prop.strip()] = value.strip()
        
        return properties
    
    def _set_nested_property(self, properties: dict, nested_key: str, value: Any):
        """设置嵌套属性"""
        parts = nested_key.split('.')
        current = properties
        
        # 创建嵌套字典结构
        for part in parts[:-1]:
            if part not in current:
                current[part] = {}
            current = current[part]
        
        # 设置最终值
        current[parts[-1]] = value
    
    def apply_element_style(self, component_type: str, style_props: dict = None) -> dict:
        """
        应用Element UI风格的组件样式
        
        Args:
            component_type: 组件类型（如 'button', 'input', 'table'）
            style_props: 额外的样式属性
            
        Returns:
            dict: 完整的组件样式配置
        """
        # 获取组件的默认样式配置
        component_config = theme_manager.get_component_config(component_type)
        
        # 构建样式字典
        style = {}
        
        # 添加组件基础样式
        if component_config:
            style.update(component_config)
        
        # 添加额外样式属性
        if style_props:
            style.update(style_props)
        
        # 解析所有样式值中的主题变量
        resolved_style = {}
        for key, value in style.items():
            resolved_style[key] = self.resolver.resolve_style_value(str(value))
        
        return resolved_style
    
    def create_button_style(self, button_type: str = "default", size: str = "default", plain: bool = False) -> dict:
        """
        创建Element UI风格的按钮样式
        
        Args:
            button_type: 按钮类型 (default, primary, success, warning, danger, info)
            size: 按钮尺寸 (large, default, small, mini)
            plain: 是否为朴素按钮
        """
        base_style = self.apply_element_style("button")
        
        # 获取组件配置
        button_config = theme_manager.get_component_config("button")
        
        # 基础样式
        style = {
            # 基本属性
            "font-family": button_config.get("font-family", "Helvetica Neue,Helvetica,PingFang SC,Hiragino Sans GB,Microsoft YaHei,SimSun,sans-serif"),
            "font-weight": button_config.get("font-weight", "500"),
            "border-width": button_config.get("border-width", "1px"),
            "border-style": button_config.get("border-style", "solid"),
            "border-radius": Theme.get_size("border-radius-base"),
            "cursor": "pointer",
            "box-sizing": "border-box", 
            "outline": "none",
            "transition": "0.1s",
            "user-select": "none",
            "vertical-align": "middle",
            "text-align": "center",
            "line-height": "1",
            "white-space": "nowrap",
            "appearance": "none",
            "display": "inline-block",
            "text-decoration": "none",
        }
        
        # 尺寸样式
        size_config = button_config.get(size, button_config.get("default", {}))
        if size_config:
            style.update({
                "height": size_config.get("height", "32px"),
                "padding": size_config.get("padding", "8px 15px"),
                "font-size": size_config.get("font-size", "14px"),
            })
        
        # 颜色样式
        color_key = f"plain-{button_type}" if plain else f"{button_type}-colors"
        colors_config = button_config.get(color_key)
        
        if not colors_config and plain:
            # 如果没有朴素样式配置，回退到普通样式
            color_key = f"{button_type}-colors"
            colors_config = button_config.get(color_key)
        
        if colors_config:
            # 正常状态
            style.update({
                "color": colors_config.get("color", "#606266"),
                "background-color": colors_config.get("background-color", "#ffffff"),
                "border-color": colors_config.get("border-color", "#dcdfe6"),
            })
            
            # 悬停状态
            hover_style = {}
            if "hover-color" in colors_config:
                hover_style["color"] = colors_config["hover-color"]
            if "hover-background-color" in colors_config:
                hover_style["background-color"] = colors_config["hover-background-color"]
            if "hover-border-color" in colors_config:
                hover_style["border-color"] = colors_config["hover-border-color"]
            
            if hover_style:
                style["hover"] = hover_style
            
            # 激活状态
            active_style = {}
            if "active-color" in colors_config:
                active_style["color"] = colors_config["active-color"]
            if "active-background-color" in colors_config:
                active_style["background-color"] = colors_config["active-background-color"]
            if "active-border-color" in colors_config:
                active_style["border-color"] = colors_config["active-border-color"]
            
            if active_style:
                style["active"] = active_style
            
            # 禁用状态
            disabled_style = {
                "color": colors_config.get("disabled-color", "#c0c4cc"),
                "background-color": colors_config.get("disabled-background-color", "#ffffff"),
                "border-color": colors_config.get("disabled-border-color", "#ebeef5"),
                "cursor": "not-allowed",
            }
            style["disabled"] = disabled_style
            
            # 聚焦状态
            if "focus-border-color" in colors_config:
                style["focus"] = {
                    "border-color": colors_config["focus-border-color"],
                    "outline": f"0px solid {colors_config['focus-border-color']}",
                }
        
        return style
    
    def create_input_style(self, size: str = "medium", state: str = "normal") -> dict:
        """
        创建输入框样式
        
        Args:
            size: 输入框尺寸 (large, medium, small, mini)
            state: 输入框状态 (normal, hover, focus, disabled, error)
        """
        base_style = self.apply_element_style("input")
        
        # 状态样式映射
        state_styles = {
            "normal": {
                "border-color": Theme.get_color("border-base"),
                "background-color": Theme.get_color("white"),
                "color": Theme.get_color("text-regular"),
            },
            "hover": {
                "border-color": Theme.get_color("primary-light-5"),
            },
            "focus": {
                "border-color": Theme.get_color("primary"),
                "box-shadow": f"0 0 0 2px {Theme.get_color('primary-light-8')}",
            },
            "disabled": {
                "background-color": Theme.get_color("fill-light"),
                "border-color": Theme.get_color("border-lighter"),
                "color": Theme.get_color("text-placeholder"),
            },
            "error": {
                "border-color": Theme.get_color("danger"),
                "color": Theme.get_color("danger"),
            },
        }
        
        # 尺寸样式映射（复用按钮的尺寸定义）
        size_styles = {
            "large": {"height": Theme.get_size("component-size-large")},
            "medium": {"height": Theme.get_size("component-size-medium")},
            "small": {"height": Theme.get_size("component-size-small")},
            "mini": {"height": Theme.get_size("component-size-mini")},
        }
        
        # 合并样式
        style = {}
        style.update(base_style)
        style.update(state_styles.get(state, state_styles["normal"]))
        style.update(size_styles.get(size, size_styles["medium"]))
        
        return self.parse_css_style(style)
    
    def clear_cache(self):
        """清空样式缓存"""
        self._style_cache.clear()
        self.component_styles.clear()
    
    def invalidate_cache_for_theme(self):
        """主题变更时使缓存失效"""
        self.clear_cache()


# =============================================================================
# 全局样式引擎实例
# =============================================================================

# 创建全局样式引擎实例
style_engine = StyleEngine()

# 注册主题变更监听器，用于清理缓存
def on_theme_changed(event):
    """主题变更时清理样式缓存"""
    style_engine.invalidate_cache_for_theme()

theme_manager.subscribe_theme_change(on_theme_changed)

# 便捷的全局函数
def parse_css(css_style: Union[str, dict]) -> dict:
    """解析CSS样式"""
    return style_engine.parse_css_style(css_style)

def create_button_style(button_type: str = "default", size: str = "default", plain: bool = False) -> dict:
    """创建按钮样式"""
    return style_engine.create_button_style(button_type, size, plain)

def create_input_style(size: str = "medium", state: str = "normal") -> dict:
    """创建输入框样式"""
    return style_engine.create_input_style(size, state)

class StyleEngine:
    """样式引擎"""
    
    def __init__(self, theme_manager):
        self.theme_manager = theme_manager
        self._style_cache = {}
    
    def parse_qml_style(self, style_object):
        """解析QML样式对象"""
        # 这里应该是将样式对象解析为实际的QML属性
        # 为了简化，我们直接返回对象
        return style_object
    
    def map_css_to_qml(self, css_style):
        """将CSS样式映射到QML属性"""
        qml_properties = {}
        
        # 背景颜色
        if "background-color" in css_style:
            qml_properties["color"] = css_style["background-color"]
        
        # 边框
        if "border" in css_style:
            border_parts = css_style["border"].split(" ")
            if len(border_parts) >= 3:
                qml_properties["border.width"] = border_parts[0]
                qml_properties["border.color"] = border_parts[2]
        
        # 文本颜色
        if "color" in css_style:
            qml_properties["textColor"] = css_style["color"]
        
        # 字体大小
        if "font-size" in css_style:
            qml_properties["font.pixelSize"] = css_style["font-size"].replace("px", "")
        
        return qml_properties
    
    def apply_style(self, component, style):
        """为组件应用样式"""
        # 这里应该是将样式应用到实际的QML组件
        # 为了简化，我们只是打印信息
        print(f"Applying style to {component}: {style}")
    
    def update_styles(self):
        """批量更新样式"""
        # 当主题变更时，更新所有组件的样式
        print("Updating all styles")